﻿using Linq2Rest.Provider;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Xinchen.SOA.Client
{
    public class JsonNetSerializerFactory : ISerializerFactory
    {
        public ISerializer<T> Create<T>()
        {
            return new JsonNetSerializer<T>();
        }

        public class JsonNetSerializer<T> : ISerializer<T>
        {
            public T Deserialize(string input)
            {
                if (string.IsNullOrWhiteSpace(input))
                {
                    return default(T);
                }
                return JsonConvert.DeserializeObject<T>(input);
            }

            public IList<T> DeserializeList(string input)
            {
                if (string.IsNullOrWhiteSpace(input))
                {
                    return new List<T>();
                }
                return JsonConvert.DeserializeObject<IList<T>>(input);
            }

            public T Deserialize(System.IO.Stream input)
            {
                if (input == null)
                {
                    return default(T);
                }
                using (var sr = new StreamReader(input))
                {
                    var s = sr.ReadToEnd();
                    return Deserialize(s);
                }
            }

            public IEnumerable<T> DeserializeList(System.IO.Stream input)
            {
                if (input == null)
                {
                    return new List<T>();
                }
                using (var sr = new StreamReader(input))
                {
                    var s = sr.ReadToEnd();
                    return DeserializeList(s);
                }
            }

            public System.IO.Stream Serialize(T item)
            {
                var stream = JsonConvert.SerializeObject(item);
                return new MemoryStream(Encoding.UTF8.GetBytes(stream));
            }
        }

        public ISerializer<T> Create<T, TSource>()
        {
            return new JsonNetSerializer<T>();
        }
    }
}
